import logging
from flask import current_app, jsonify,render_template,request,session
from flask import g

from info import constants
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info import redis_store

# 请求路径: /
# 请求方式: GET
# 请求参数: 无
# 返回值: index.html页面, data数据
# 装饰器的作用是将路由映射到视图函数index
@index_blue.route("/",methods=["get", "post"])
@user_login_data
def show_index():
    # redis_store.set("name", "laowang")
    # print(redis_store.get("name"))
    # session["name"] = "xiaowang"
    # print(session.get("name"))

    # logging.debug("调试模式")
    # logging.info("调试模式")
    # logging.warning("调试模式")
    # logging.error("调试模式")

    # logging.debug("调试模式")
    # logging.info("调试模式")
    # logging.warning("调试模式")
    # logging.error("调试模式")
    # 获取用户登录状态,取session的值用get方法，不会发生错误
    # user_id = session.get("user_id")
    #
    # user = None
    #
    # if user_id:
    #     try:
    #         # 获取用户登录数据
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 按点击量降序排行前十的新闻
    try:
        categories = Category.query.all()
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logging.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻失败")

    # 创建列表保存分类信息
    category_list = []
    # 保存分类信息
    for cate in categories:
        category_list.append(cate.to_dict())
    # 创建列表保存10条新闻
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())
    # 携带用户数据渲染到页面中
    data = {
        "user_info":g.user.to_dict() if g.user else "",
        "click_news_list":click_news_list,
        "category_list":category_list

    }

    return render_template("news/index.html",data = data)


# 处理网站logo
"""
- 1.在后台提供一个接口, /favicon.ico,返回一张图片即可
- 2.使用使用current_app.send_static_file(文件名A),寻找static文件夹中的文件A
"""
@index_blue.route("/favicon.ico")
def web_logo():
    return current_app.send_static_file("news/favicon.ico")

# 9.首页新闻列表
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据

@index_blue.route('/newslist')
def newslist():
    # 获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")

    # 参数转换成整形，方便分页查询
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    # 分页查询
    try:
        query_condition = ""
        if cid != "1":
            query_condition = News.category_id == cid
        paginate = News.query.filter(query_condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="新闻获取失败")

    # 获取分页对象身上的属性，总页数，当前页，当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 将对象列表转换成字典列表
    newsList = []
    for item in items:
        newsList.append(item.to_dict())

    # # 拼接数据
    # data = {
    #     "totalPage":totalPage,
    #     "currentPage":currentPage,
    #     "newsList":newsList
    # }

    return jsonify(errno=RET.OK, errmsg="获取数据成功",
                   totalPage=totalPage,currentPage=currentPage,
                   newsList=newsList)
